/*
 * Copyright (C) 2018, All rights Reserved, Designed By www.xiniaoyun.com
 * Auto created by xny_code_generator
 * @Copyright: 2018 www.xiniaoyun.com Inc. All rights reserved.
 * 注意：本内容仅限于犀鸟云公司内部传阅，禁止外泄以及用于其他的商业目的
 *
 */

package com.huey.utils.message;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 */
@Component
public class MessageUtils {

    private static Logger logger= LoggerFactory.getLogger(MessageUtils.class);


    private static MessageSource messageSource;

    /**
     * 在Spring里，静态变量/类变量不是对象的属性，而是一个类的属性，不能用@Autowired一个静态变量（对象），使之成为一个SpringBean。<br />
     * 只能通过setter方法注入，并把类注解成为组件
     * @param messageSource
     */
    @Autowired
    public void init(MessageSource messageSource) {
        MessageUtils.messageSource = messageSource;
    }


    public static String getMessageWithLocale(String code, Object... args) {
        Locale locale = LocaleContextHolder.getLocale();
        String message = null;
        try{
            message = messageSource.getMessage(code, args, locale);
        }catch (NoSuchMessageException e){
            message = String.format(code, args);
            logger.error("NoSuchMessageException:"+message,e);
        }
        return message;
    }
}
